package com.hll.api.controller.xinhua;

import com.hll.api.config.web.RespMessage;
import com.hll.api.entity.ShopCar;
import com.hll.api.entity.User;
import com.hll.api.service.IShopCarService;
import com.hll.api.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 购物车
 * @author 何龙笼
 * @create 2019-07-14 9:18
 */
@RestController("xinhuaShopCarController")
@RequestMapping("/api/xinhua/shopcar")
public class ShopCarController {
	@Resource
	IShopCarService service;

	@Resource
	UserService userService;


	@DeleteMapping("/delete")
	public RespMessage del(String goodsId, HttpServletRequest session){
		if (goodsId==null){
			return RespMessage.error("商品id不能为空");
		}

		User user = userService.getXinhuaUser(session);
		ShopCar shopCar = service.getShopCar(goodsId, user.getId().intValue());
		if (shopCar == null) {
			return RespMessage.error("商品不存在");
		}
		service.removeById(shopCar.getId());
		return RespMessage.success("删除成功");
	}


	@PutMapping("/update")
	public RespMessage update(String goodsId,Integer num,HttpServletRequest session){
		if (goodsId==null||num==null){
			return RespMessage.error("商品id和数量不能为空");
		}
		if (num<=0){
			return RespMessage.error("数量不能小于0");
		}
		User user = userService.getXinhuaUser(session);
		ShopCar shopCar = service.getShopCar(goodsId, user.getId().intValue());
		if (shopCar == null) {
			return RespMessage.error("商品不存在");
		}
		shopCar.setNum(num);
		service.updateById(shopCar);
		return RespMessage.success("修改成功");
	}

	@GetMapping("/get")
	public RespMessage get(HttpServletRequest session){
		User user = userService.getXinhuaUser(session);
		List<ShopCar> shopCarList = service.getShopCarList(user);
		return RespMessage.success(shopCarList,null);
	}

	@PostMapping("/add")
	public RespMessage add(ShopCar shopCar, HttpServletRequest session){
		if (shopCar==null||shopCar.getGoodsId()==null|| StringUtils.isEmpty(shopCar.getName())){
			return RespMessage.error("商品id、商品名不能为空");
		}
		User user = userService.getXinhuaUser(session);
		ShopCar shopCar1 = service.getShopCar(shopCar.getGoodsId(), user.getId().intValue());
		shopCar.setNum(1);
		if (shopCar1!=null){
			shopCar.setNum(shopCar1.getNum()+1);
			shopCar.setId(shopCar1.getId());
		}
		shopCar.setDate(new Date());
		shopCar.setUserId(user.getId().intValue());
		service.saveOrUpdate(shopCar);
		return RespMessage.success("增加成功");
	}
}
